<template>
  <div>
    <el-card style="width: 100%">
      <p class="pinformation">搜索条件</p>
      <el-form label-width="80" ref="queryRef" :model="queryParams">
        <el-row>
          <el-col :span="4">
            <el-form-item label="方案编号：" prop="projectCode">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入方案编号"
                v-model="queryParams.projectCode"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="委托单位：" prop="wtCustomName">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入委托单位"
                v-model="queryParams.wtCustomName"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="方案名称：" prop="projectName">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入方案名称"
                v-model="queryParams.projectName"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="样品编号：" prop="sampleCode">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入样品编号"
                v-model="queryParams.sampleCode"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="检测项目：" prop="jcxmName">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入检测项目"
                v-model="queryParams.jcxmName"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="方法编号：" prop="methodCode">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入方法编号"
                v-model="queryParams.methodCode"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="4">
            <el-form-item label="采样时间：">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="紧急类型：" prop="degree">
              <el-select
                v-model="queryParams.degree"
                placeholder="请选择紧急类型"
                clearable
              >
                <el-option
                  v-for="dict in proxy.addListNoLimit(sys_degree)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="交接批次：" prop="withNumber">
              <el-input
                maxlength="100"
                clearable
                placeholder="请输入交接批次"
                v-model="queryParams.withNumber"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="检测类别：" prop="jclbId">
              <el-select
                v-model="queryParams.jclbId"
                placeholder="请选择检测类别"
                clearable
              >
                <el-option
                  v-for="item in proxy.addListNoLimit(
                    jclbList,
                    'jclbId',
                    'jclbName'
                  )"
                  :key="item.jclbId"
                  :value="item.jclbId"
                  :label="item.jclbName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="分析组：" prop="userGroupId">
              <el-select
                v-model="queryParams.userGroupId"
                placeholder="请选择分析组"
                clearable
              >
                <el-option
                  v-for="dict in proxy.addListNoLimit(sys_user_group)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-row justify="center">
              <el-button type="success" @click="handleQuery">搜索</el-button>
              <el-button class="business resetBtn" @click="resetQuery"
                >重置</el-button
              >
            </el-row>
          </el-col>
        </el-row>
      </el-form>

      <el-row>
        <p class="pinformation" style="margin-top: 8.5px">样品列表</p>
        <p class="totalStyle" style="margin-top: 6px">共 {{ total }} 条数据</p>
        <!-- <el-row style="padding-bottom: 5px; margin-left: 25px">
          <el-button link type="success">扫码领样</el-button>
          <el-form-item
            label="扫码结果："
            prop=""
            style="margin-bottom: 0px !important; margin-left: 15px"
          >
            <el-input maxlength="100" clearable placeholder="请输入扫码结果" />
          </el-form-item>
          <el-button link type="success" style="margin-left: 25px"
            >批量领用</el-button
          >
        </el-row> -->
      </el-row>

      <el-table
        ref="mainTableRef"
        :data="sampleList"
        v-loading="loading"
        border
        @select="handleCheckbox"
        @select-all="handleAllCheckbox"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          show-overflow-tooltip
          label="样品编号"
          align="center"
          prop="sampleCode"
          width="150"
        />
        <el-table-column
          show-overflow-tooltip
          label="检测项目"
          align="center"
          prop="jcxmName"
        >
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="方案编号"
          align="center"
          prop="projectCode"
          width="150"
        />
        <el-table-column
          show-overflow-tooltip
          label="方案名称"
          align="center"
          prop="projectName"
        />
        <el-table-column
          show-overflow-tooltip
          label="方法编号"
          align="center"
          prop="methodCode"
          width="150"
        />
        <el-table-column
          show-overflow-tooltip
          label="方法名称"
          align="center"
          prop="methodName"
          width="250"
        />
        <el-table-column
          show-overflow-tooltip
          label="保存时长"
          align="center"
          prop="saveTime"
        >
          <template #default="scope"
            >{{ scope.row.saveTime }}{{ scope.row.timeUnitName }}</template
          >
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="保存方式"
          align="center"
          prop="saveDesc"
        />
        <el-table-column
          show-overflow-tooltip
          label="交接批次"
          align="center"
          prop="withNumber"
        />
        <el-table-column
          show-overflow-tooltip
          label="检测类别"
          align="center"
          prop="jclbName"
        />
        <el-table-column
          show-overflow-tooltip
          label="分析组"
          align="center"
          prop="userGroupName"
        />
      </el-table>
      <el-row>
        <el-col :span="12">
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            v-model:pageSizes="pageSizes"
            @pagination="getList"
          />
        </el-col>
        <el-col
          :span="12"
          style="text-align: right; margin-top: 20px; padding-right: 20px"
        >
          <span style="margin-right: 15px">已选中 {{ count }} 条</span>
          <el-button type="danger" @click="handleAllRemove" :disabled="!count"
            >清空选中</el-button
          >
          <el-button type="success" @click="handleDefine" :disabled="!count"
            >生成样品发放表</el-button
          >
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import {
  getSelectSampleList,
  addSelectSample,
  removeSelectSample,
  removeAllSelectSample,
  defineSelectSample,
  getSampleJcxmCount,
  getTaskId,
} from "@/api/sampleManage/sampleGet";
import useRouteView from "@/store/modules/routeView";
import { allListJclb } from "@/api/store/jclb";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { sys_degree } = proxy.useDict(
  "sys_degree",
);
const {  sys_user_group } = proxy.useOrgDict(
  "sys_user_group"
);
const jclbList = ref([]);
const dateRange = ref([]);
const queryParams = ref({ pageNum: 1, pageSize: 50 });
const sampleList = ref([]);
const loading = ref(false);
const total = ref(0);
const count = ref(0);
const getId = ref();
const routeViewStore = useRouteView();
const pageSizes = ref([50, 100, 150, 200]);
function getList() {
  loading.value = true;
  getSelectSampleList(
    proxy.addDateRange(queryParams.value, dateRange.value)
  ).then((res) => {
    loading.value = false;
    sampleList.value = res.rows;
    total.value = res.total;
    nextTick(() => {
      sampleList.value.forEach((item) => {
        if (item.getId) {
          proxy.$refs["mainTableRef"].toggleRowSelection(item, true);
          if (!getId.value) {
            getId.value = item.getId;
          }
        }
      });
    });
  });
}
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handleQuery();
}

getList();
getCount();

function getCount() {
  getSampleJcxmCount().then((res) => {
    count.value = res.data.count;
    getId.value = res.data.getId;
  });
}

allListJclb().then((res) => {
  jclbList.value = res.data;
});

// ---------------------------勾选复选框提交------------------------
function handleCheckbox(selection, row) {
  if (!row.getId) {
    addSelectSample({
      getId: getId.value,
      projectSampleJcxmList: [{ sJId: row.sJId, userGroupId: row.userGroupId }],
    }).then((res) => {
      if (!getId.value) getId.value = res.data;
      row.getId = getId.value;
      count.value++;
    });
  } else {
    removeSelectSample({ sJIds: [row.sJId], getId: row.getId }).then((res) => {
      count.value--;
      delete row.getId;
    });
  }
}

function handleAllCheckbox(selection) {
  if (selection.length > 0) {
    let jsonData = {
      getId: getId.value,
      projectSampleJcxmList: selection.map((item) => {
        return { sJId: item.sJId, userGroupId: item.userGroupId };
      }),
    };
    addSelectSample(jsonData).then((res) => {
      if (!getId.value) getId.value = res.data;
      selection.forEach((item) => {
        item.getId = getId.value;
      });
      getCount();
    });
  } else {
    removeSelectSample({
      sJIds: sampleList.value.map((item) => item.sJId),
      getId: getId.value,
    }).then((res) => {
      getCount();
    });
    sampleList.value.forEach((item) => {
      delete item.getId;
    });
  }
}

function handleAllRemove() {
  proxy.$modal.confirm("您当前已经选择了样品，确认要全部删除吗？").then(() => {
    removeAllSelectSample(getId.value).then((res) => {
      count.value = 0;
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
  });
}

function handleDefine() {
  proxy.$modal.confirm("确认要生成样品发放表吗？").then(() => {
    proxy.$modal.loading("正在样品发放表，请稍候...");
    defineSelectSample(getId.value)
      .then((res) => {
        proxy.$modal.msgSuccess("生成样品发放表成功");
        if (res.data) {
          if (routeViewStore.routeView1) {
            proxy.$tab.closePage(routeViewStore.routeView1);
          }
          router.push({
            path: "/flowable/task/record/index",
            query: {
              deployId: res.data.deployId,
              procInsId: res.data.procInsId,
              executionId: res.data.executionId,
              taskId: res.data.taskId,
              finished: true,
              path: "/task/todo",
            },
          });
          handleQuery();
          proxy.$modal.closeLoading();
        } else {
          proxy.$modal.msgError("流程启动失败，未到找到样品发放流程！");
        }
      })
      .catch((res) => {
        proxy.$modal.msgError("流程启动失败，未到找到样品发放流程！");
        proxy.$modal.closeLoading();
      });
  });
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 74 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 74 }];
    }
    getTableHeight();
  }
);

watch(
  () => route,
  (newVal) => {
    if (newVal.path == "/flowable/task/record/index") {
      const { path, name, meta } = newVal;
      routeViewStore.setRouteView1({ path, name, meta });
    }
  }
);

const heightParams = ref([{ tableName: "main", bottomHeight: 74 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});
</script>
